<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/webpage/include/taglib.jsp" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html style="overflow: auto;">
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>植百汇库存校核单</title>
    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/jquery-1.10.2.min.js"></script>
    <%@ include file="/webpage/include/bootstraptable.jsp"%>
    <%@include file="/webpage/include/treeview.jsp" %>
    <%@include file="warehouseForm.jsp" %>
    <script>
        var ctx = '${ctx}';
    </script>

    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/layui.js"></script>
    <link rel="stylesheet" href="${ctxStatic}/common/css/app-blue.css" media="all"> 
    

    <script src="${ctxStatic}/common/js/jeeplus.js"></script> 
    <link rel="stylesheet" href="${ctxStatic}/inventoryCheck/addInventory.css" media="all"> 
    <script>
    $(document).ready(
        function(){
        var c = $(window.parent.document.body) 
            c.find('.layui-layim-min').hide();
        }
    );
    $(window).unload(function(){
        console.log("Goodbye");
        var c = $(window.parent.document.body) 
            c.find('.layui-layim-min').show();
    });
    </script>


</head>
<body style="width:100%; height:100%; overflow: scroll; -webkit-overflow-scrolling: touch;">
	<div class="wrapper wrapper-content">				
			<div class="row">
				<div class="col-md-12">
					<div class="panel panel-primary">
						<div class="panel-heading">
							<h3 class="panel-title"> 
								<a class="panelButton" href="${ctx}/sc/check/index"><i class="ti-angle-left"></i> 返回</a>
							</h3>
						</div>
						<div class="panel-body">
						    <form class="layui-form" action="">
						        <!--供应商信息start-->
						        <!--供应商信息end-->
						    
						        <div class="row remarkRow">
							        <div class="col-xs-12 col-sm-9 col-md-9 ">
							        	 <label class='label-txt col-xs-4 col-sm-3 '>备注:</label>
							            <div class="layui-input-inline col-xs-8 col-sm-11">
							                <textarea id="remarks" name="remarks" placeholder="请输入内容" class="layui-textarea"></textarea>
							            </div>
							        </div>
						        </div>
						         <!-- 工具栏 -->
						         <div id="toolbar">
				                        <span  class="btn btn-danger" onclick="subForm()">
				                            <i class="glyphicon glyphicon-save"></i>保存
				                        </span>
				                </div>
				                <!-- 工具栏 -->
						        <style>
						                #purchaseOrder .self-adaption-wrap {
						                   overflow-x: scroll;
						               }
						               .self-adaption-wrap::-webkit-scrollbar {
						                   display: none;
						               }
						               #purchaseOrder .self-adaption-input{
						                   min-width: 200px;
						               }
						        </style>
						        <!--动态添加数据start-->
						        <div class="flex-bet ma-t10 tables">
						        	<div class="w-45p">
						        		<div class="table-heading flex-bet">
											<h3 class="panel-title pa-t6"> 
												<i class="ti-angle-left"></i> 入库</a>
											</h3>
											<a  class="btn btn-info" href="javascript:;"  onclick="sub('in')"><i
				                                class="glyphicon glyphicon-plus"></i> 选择SKU</a>
										</div>
						        		<table id="inventoryIn"></table>
						        	</div>
						        	<div class="w-45p">
						        		<div class="table-heading flex-bet">
											<h3 class="panel-title pa-t6"> 
												<i class="ti-angle-left"></i> 移库</a>
											</h3>
											<a  class="btn btn-info" href="javascript:;"  onclick="sub('out')"><i
				                                class="glyphicon glyphicon-plus"></i> 选择SKU</a>
										</div>
						        		<table id="inventoryOut"></table>
						        	</div>
						        </div>
						        <!--动态添加数据end-->
						        <hr/>
						    </form>
						</div>
					</div>
				</div>
			</div>
		</div>
 </body>

<!-- layUI 加载form属性 -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;

        <!--供应商和供应商合同关联-->
        form.on('select(supplierId)', function (data) {
            var ins = $("#iv").find(".a");
            $("#contractId").empty();
            var html = ""
            for (var i = 0; i < ins.length; i++) {
                if ($(ins[i]).attr("id") == data.value) {
                    var name = $(ins[i]).attr("name");
                    var id = $(ins[i]).attr("value");
                    html += "<option value='" + id + "'>" + name + "</option>";
                }
            }
            $("#contractId").append(html);
            form.render();
        });
    });
</script>
<script type="text/javascript">
    function getItems(tableId){
  	  //入库/移库明细单
	    var items = $(tableId+">tbody>tr");
	    if(null==items || ""==items || items.length==0){
	        return [];
	    }
	    var orderItems = new Array();
	    var orderItem;
	    for (var i = 0; i < items.length; i++) {
	        orderItem = new Object();
	        orderItem.skuId = $(items[i]).find("[name='skuId']").val();
	        orderItem.amount = $(items[i]).find("#num").val();
	        if (orderItem.skuId == ""|| orderItem.amount == "") {
	            layer.alert('有空数据请检查!', {
	                icon: 2,
	                title: "提示"
	            }); 
	           // jp.error("有空数据！");
	            return;
	        }
	        if(orderItem.amount == "0"){
	        	layer.alert('数量不可以为0!', {
	                icon: 2,
	                title: "提示"
	            }); 
	            return;
	        }
	        //移动端数字处理
	        var reg = /^[1-9]\d*$/;
	        if(orderItem.amount){
	        	if(!reg.test(orderItem.amount)){
		        	layer.alert('数量不可包含非数字', {
		                icon: 2,
		                title: "提示"
		            }); 
		            return;
		        }
	        	orderItems.push(orderItem);
	        }
	    }
	    return orderItems;
    }
	function subForm(){
		var json = new Object();
	    let comment = $("#remarks").val();//备注
        let inItems = getItems("#inventoryIn");
	    let outItems = getItems("#inventoryOut");
	    if(!inItems&&!outItems||(inItems.length<=0&&outItems.length<=0)){
	    	layer.alert('请添加sku!', {
	            icon: 2,
	            title: "提示"
	        });
	    	return;
	    }
	    var fromData = new FormData();
	    fromData.append("comment",comment); 
	    if(inItems.length>0){
	    	fromData.append("in",JSON.stringify(inItems)); 
	    }
	    if(outItems.length>0){
	    	fromData.append("out",JSON.stringify(outItems)); 
	    }
	    //提交数据
 	    $.ajax({
	        url: "${ctx}/sc/check/save",
	        type: "post",
	        data: fromData,
	        contentType: false, // 注意这里应设为false
	        processData: false,
	        beforeSend: function () {
	            index = layer.load(1, {
	                shade: [0.5, '#fff'] //0.1透明度的白色背景
	            });
	        },
	        complete: function () {
	            layer.close(index);
	        },
	        success: function (data) {
	            if (data.message == "0") {
	                layer.alert('保存成功!', {
	                    icon: 1,
	                    title: "提示"
	                });
	                layer.close(index);
	                reBack();
	            }else{
	            	layer.alert(data.data, {
	                    icon: 2,
	                    title: "提示"
	                });
	               // layer.close(index);
	            }
	        },
	        error: function (e) {
	            layer.alert('保存失败!', {
	                icon: 2,
	                title: "提示"
	            });

	        }
	    }); 
	}
</script>
<script>
    <!--返回方法-->
    function reBack() {
        window.location.href = "${ctx}/sc/check/index";
    }



</script>
<%-- <scrip src="${ctxStatic}/purchase/add_purchase.js"></scrip> --%> 
 <script src="${ctxStatic}/plugin/bootstrapTable/bootstrap-table.js"></script> 
<script src="${ctxStatic}/plugin/bootstrapTable/bootstrap-table-zh-CN.js"></script>  
<script>
let currentDatas = [];
//创建表格数据(非url请求)-选择SKUP
function createTableData(tableId,sourceData){
	let numTitle = tableId=="#inventoryIn"?'入库数量':'移库数量';
 	$(tableId).bootstrapTable({
 	   data:sourceData,
  	   striped: true,
	  	columns: [
	  	   {
	 			title: '序号', //标题 可不加
	 			field:'scount',
	 			formatter: function (value, row, index) {
	 				return index + 1;
	 			},
	 	   },
	 	   {
	 		   title:'SKUID',
	 		   field:'skuId',
		       formatter:function(value,row,index){
		       	return '<input class="noborder" value='+row.skuId+' name="skuId" readOnly>';
		       },
	 	   },
	 	   {
	 	      field:'',
		      title: 'SKU',
		      formatter:function(value,row,index){
		       	return row.firstType+"-"+row.secondType+"-"+row.thirdType;
		      }
		   },
		   {
		       field: 'amount',
		       title: numTitle,
		       class:'no-padding',
		       formatter:function(value,row,index){
		    	   let autoStr =tableId=="#inventoryIn"?'入库数量':'移库数量';
		    	   return '<input class="form-input" onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入'+autoStr+'数量">';
		       }
		   }, 
		   {
	       		title: '操作',
	       		formatter:function(value,row,index){
	       			return "<span class='btn btn-danger table-btn ' onclick='removeItem(this,\""+tableId+"\","+row.skuId+")'>删除</span>";
		        }
	       }
	 ]
  });
}

    //弹窗选择sku
    function sub(type) {
        layer.open({
            type: 2,
            title: 'sku选择',
            maxmin: true, //开启最大化最小化按钮*!/
            area: ['96%', '80%'],
            offset: '10px',
            content:ctx+"/sku/sku/pop2",
            btn:['确定','取消'],
            yes : function(index,layero) {
                var rowsO=$(layero).find("iframe")[0].contentWindow.$("#skuTable");
            	var rows = rowsO.bootstrapTable('getSelections');
                let tableId;
                if(type=="in"){
                	tableId = "#inventoryIn";
                }else if(type=='out'){
                	tableId = "#inventoryOut";
                }
                if(null!=rows){
                	for(let i=0;i<rows.length;i++){
                		let o= rows[i];
                		let res=checkSkuId(o.skuId);//校验是否重复
                   	 	if(res){//当前重复 删除该对象
                       	 	rows.splice(i,1);
                   	 	    i--;
	                     }
                   	 	console.log("====删除重复之后的rows",rows);
                	}
                	var count = $(tableId).bootstrapTable('getData').length;
                	var dataArr = $(tableId).bootstrapTable('getData');
                	var hasThead = $(tableId+'>thead').length;
                	if(hasThead>0){
                		var nextIndex;
                		for(var i = 0; i < count; i++){
                        	// 获取父级元素
              	           	var eleParent = $(tableId+'>tbody>tr:eq('+i+')');
              	          	// 获取每个row对应field的值
              	          	dataArr[i]['amount'] = eleParent.find("[name='num']").val();
              	          	// 更新option中的值
              	           	$(tableId).bootstrapTable('getOptions').data.splice(i, 1, dataArr[i]);
                    	}
                		$.each(rows,function(idx,o){
	                       	 // 新建下一个row
		                        var insertRow = o;
		                        // 给下一个row赋值
		                        var params = {index:count + 1, row:insertRow};
		                        $(tableId).bootstrapTable('insertRow', params);
		                     //}
	                   	});
                	}else{
                		createTableData(tableId,rows);
                	}
                }
            }
        });
    }
    //校验sku是否重复
    function checkSkuName(tableId,id) {
        var k=0;
        var skus=$(tableId).find("input[name='skuId']");
        for(var i=0;i<skus.length;i++){
            if(id==$(skus[i]).val()){
               // layer.alert('已存在相同的sku!', {
                   // icon: 3,
                   // title: "提示"
                //});
                k=1;
            }
        }
        return k;
    }
    function checkSkuId(id){
    	 var k=0;
         var skus=$(".tables").find("input[name='skuId']");
         for(var i=0;i<skus.length;i++){
             if(id==$(skus[i]).val()){
                 layer.alert('已存在相同的sku!', {
                    icon: 3,
                    title: "提示"
                 });
                 k=1;
             }
         }
         return k;
    }

    //删除
    function removeItem(obj,tableId,skuId) {
    	 jp.confirm('确认要删除该SKU吗？', function(){
    		var $patr =$(obj).parents("tr");
    		//将该数据从数据源删除 
    		rowData =$(tableId).bootstrapTable('getData');
    		//记录当前页面填写的数据
    		var $currentTrs = $(tableId+">tbody>tr:not(.detail-view)");
    		for(var x=0;x<$currentTrs.length;x++){
    			var $tr = $($currentTrs[x]);
    			var currentSkuId = $tr.find("[name='skuId']").val();
    			if(currentSkuId==rowData[x].skuId){
    				//格式修改
    				rowData[x].amount=$tr.find("[name='num']").val()||'""';
    			}
    		}
    		for(var i=0;i<rowData.length;i++){
    			var o = rowData[i];
    			if(o.skuId==skuId){
    				rowData.splice(i,1);
    			}
    		}
    		if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//手机端
    			var $patr =$(obj).parents("tr");
   	    	 	$patr.next(".detail-view").remove();
   	    	    $patr.remove();
    		}else{//pc端
   	    	 	$(tableId).bootstrapTable("destroy");
 			 	createTableData(tableId,rowData);
    		}
		}) 
    } 
    //数量
    function checkAmount(obj){
    	obj.value=obj.value.replace(/\D/g,'');
    }

</script>
</html>
